import { goodsList, goodsCount } from "../../request/api";

const state = {
    list: [],
    // 总条数
    total: 0,
    // 每页的条数
    size: 2,
    page: 1
}

const mutations = {
    changeList(state, arr) {
        state.list = arr
    },
    changeTotal(state, num) {
        state.total = num
    },
    changePage(state, num) {
        state.page = num
    }
}

const actions = {
    //请求列表数据
    reqChangeList(context) {
        goodsList({ size: context.state.size, page: context.state.page }).then(res => {
            let list = res.data.list ? res.data.list : []
            if (list.length == 0 && context.state.page > 1) {
                context.commit("changePage", context.state.page - 1)
                context.dispatch("reqChangeList")
            }
            context.commit("changeList", list)
        })
    },
    // 请求列表总条数
    reqChangeTotal(context) {
        goodsCount().then(res => {
            context.commit("changeTotal", res.data.list[0].total)
        })
    },
    // 修改当前页码数
    reqChangePage(context, num) {
        context.commit("changePage", num)
        context.dispatch("reqChangeList")
    }
}

const getters = {
    list(state) {
        return state.list
    },
    total(state) {
        return state.total
    },
    size(state) {
        return state.size
    }
}
export default {
    state,
    mutations,
    actions,
    getters,
    namespaced: true
}